//
//  ZCAbnormalDetailViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/19.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCAbnormalDetailViewController.h"
#import "ZCAbnormalTitleTableViewCell.h"
#import "ZCAbnormalDescTableViewCell.h"
#import <AVFoundation/AVFoundation.h>
#import "ZCAbnormalSignListView.h"
#import "ZCAbnormalScanPhotoViewController.h"
#import <QiniuSDK.h>
#import <Photos/Photos.h>


static NSString *titleCellID = @"ZCAbnormalTitleTableViewCell";
static NSString *descCellID = @"ZCAbnormalDescTableViewCell";

@interface ZCAbnormalDetailViewController ()<UITableViewDelegate, UITableViewDataSource, ZCAbnormalDescTableViewCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CAAnimationDelegate, ZCAbnormalSignListViewDelegate>
@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;
@property (nonatomic, strong) UIView *handleView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *numLabel;
@property (nonatomic, strong) UIButton *abnormalDetailButton;
@property (nonatomic, strong) UIButton *signButton;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, assign) CGRect rectInScreen;
@property (nonatomic, strong) CALayer *layer;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIBezierPath *path;
@property (nonatomic, assign) int num;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) ZCAbnormalSignListView *signListView;
@property (nonatomic, strong) NSMutableArray *signArray;
@property (nonatomic, strong) ZCAbnormalSignModel *signModel;
@property (nonatomic, strong) NSString *level1Name;
@property (nonatomic, copy) NSString *currentTaskType;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCAbnormalDetailViewController
#pragma mark - 懒加载
- (UITableView *)leftTableView {
    if (!_leftTableView) {
        _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, space(210), SCREENHEIGHT - space(90)) style:UITableViewStyleGrouped];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.showsHorizontalScrollIndicator = NO;
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _leftTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _leftTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _leftTableView.scrollIndicatorInsets = _leftTableView.contentInset;
            _leftTableView.estimatedRowHeight = 0;
            _leftTableView.estimatedSectionFooterHeight = 0;
            _leftTableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_leftTableView registerClass:[ZCAbnormalTitleTableViewCell class] forCellReuseIdentifier:titleCellID];
        
    }
    return _leftTableView;
}

- (UITableView *)rightTableView {
    if (!_rightTableView) {
        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(space(210), 64, SCREENWIDTH - space(210), SCREENHEIGHT - space(90) - 64) style:UITableViewStyleGrouped];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        _rightTableView.showsHorizontalScrollIndicator = NO;
        _rightTableView.showsVerticalScrollIndicator = NO;
        _rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _rightTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _rightTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _rightTableView.scrollIndicatorInsets = _rightTableView.contentInset;
            _rightTableView.estimatedSectionHeaderHeight = 0;
            _rightTableView.estimatedSectionFooterHeight = 0;
            _rightTableView.estimatedRowHeight = 0;
        }
        [_rightTableView registerClass:[ZCAbnormalDescTableViewCell class] forCellReuseIdentifier:descCellID];
    }
    return _rightTableView;
}

- (UIView *)handleView {
    if (!_handleView) {
        _handleView = [[UIView alloc] init];
        _handleView.backgroundColor = [UIColor whiteColor];
    }
    return _handleView;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.image = [UIImage imageNamed:@"icon-abnormal"];
    }
    return _imageView;
}

- (UILabel *)numLabel {
    if (!_numLabel) {
        _numLabel = [[UILabel alloc] init];
        _numLabel.textColor = [UIColor redColor];
        _numLabel.font = [UIFont systemFontOfSize:FontSize(20)];
        _numLabel.textAlignment = NSTextAlignmentLeft;
        _numLabel.hidden = YES;
    }
    return _numLabel;
}

- (UIButton *)abnormalDetailButton {
    if (!_abnormalDetailButton) {
        _abnormalDetailButton = [[UIButton alloc] init];
        [_abnormalDetailButton setTitle:@"异常详情" forState:UIControlStateNormal];
        [_abnormalDetailButton setTitleColor:ZCColor(0xff8213, 1) forState:UIControlStateNormal];
        _abnormalDetailButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(32)];
        [_abnormalDetailButton addTarget:self action:@selector(exceptionDetail:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _abnormalDetailButton;
}

- (UIButton *)signButton {
    if (!_signButton) {
        _signButton = [[UIButton alloc] init];
        [_signButton setTitle:@"标记异常" forState:UIControlStateNormal];
        [_signButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _signButton.backgroundColor = ZCColor(0xff8213, 1);
        _signButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(32)];
        [_signButton addTarget:self action:@selector(signButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _signButton;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = ZCColor(0x000000, 0.05);
    }
    return _lineView;
}

- (NSMutableArray *)titleArray {
    if (!_titleArray) {
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}

- (UIView *)bgView {
    if (!_bgView) {
       _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
        _bgView.backgroundColor = ZCColor(0x000000, 0.4);
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgViewClick:)];
        [_bgView addGestureRecognizer:tap];
    }
    return _bgView;
}

- (ZCAbnormalSignListView *)signListView {
    if (!_signListView) {
        _signListView = [[ZCAbnormalSignListView alloc] initWithFrame:CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, space(650))];
        _signListView.delegate = self;
    }
    return _signListView;
}

- (NSMutableArray *)signArray {
    if (!_signArray) {
        _signArray = [NSMutableArray array];
    }
    return _signArray;
}

#pragma mark - 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backToHome) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.title = @"标记异常";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightTableView];
    [self.view addSubview:self.signListView];
    [self.view addSubview:self.handleView];
    [self.handleView addSubview:self.imageView];
    [self.handleView addSubview:self.numLabel];
    [self.handleView addSubview:self.abnormalDetailButton];
    [self.handleView addSubview:self.signButton];
    [self.handleView addSubview:self.lineView];
    
    [self updateViewConstraints];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 属性方法
- (void)setFromAbnormal:(BOOL)fromAbnormal {
    _fromAbnormal = fromAbnormal;
    if (fromAbnormal) {
        self.currentTaskType = @"0";
    }else {
        self.currentTaskType = self.taskType;
    }
}

#pragma mark - 按钮点击事件

- (void)backToHome {
    [self.navigationController popViewControllerAnimated:YES];
}

//异常详情
- (void)exceptionDetail:(UIButton *)sender {
    if (self.signArray.count == 0) {
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.removeFromSuperViewOnHide = YES;
        self.hud.mode = MBProgressHUDModeText;
        self.hud.label.text = @"还没有任何异常标记";
        [self.hud hideAnimated:YES afterDelay:HudTime];
    }else {
        sender.selected = !sender.selected;
        if (sender.selected) {
            self.signListView.signArray = self.signArray;
            [self.view insertSubview:self.bgView belowSubview:self.signListView];
            [UIView animateWithDuration:0.5 animations:^{
                self.signListView.frame = CGRectMake(0, SCREENHEIGHT - space(740), SCREENWIDTH, space(650));
            }];
        }else {
            [self.bgView removeFromSuperview];
            [UIView animateWithDuration:0.5 animations:^{
                self.signListView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, space(650));
            }];
        }
    }

}

//标记异常
- (void)signButtonClick:(UIButton *)sender {
    if (self.signArray.count == 0) {
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.removeFromSuperViewOnHide = YES;
        self.hud.mode = MBProgressHUDModeText;
        self.hud.label.text = @"还没有标记任何异常";
        [self.hud hideAnimated:YES afterDelay:HudTime];
    }else {
        NSMutableArray *exceptionArray = [NSMutableArray array];
        for (ZCAbnormalSignModel *signM in self.signArray) {
            ZCAbnormalExceptionModel *exceptionM = [[ZCAbnormalExceptionModel alloc] init];
            exceptionM.level2Code = signM.exLevel2;
            exceptionM.level3Code = signM.exLevel3;
            exceptionM.level2Name = signM.level2Name;
            exceptionM.level3Name = signM.level3Name;
            NSMutableString *keys = [NSMutableString string];
            for (ZCAbnormalListDetailModel *detailM in signM.exceptionDetails) {
                if (keys.length == 0) {
                    [keys appendString:detailM.picKey];
                }else {
                    [keys appendString:@","];
                    [keys appendString:detailM.picKey];
                }
            }
            exceptionM.picKeys = [keys copy];
            NSDictionary *jsonD = [exceptionM yy_modelToJSONObject];
            [exceptionArray addObject:jsonD];
        }
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:exceptionArray options:0 error:&error];
        NSString *exceptionDetails = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:self.taskType forKey:@"taskType"];
        [param setObject:self.orderNo.length > 0 ? self.orderNo : @(0) forKey:@"orderNo"];
        [param setObject:self.vin forKey:@"vin"];
        [param setObject:self.taskId forKey:@"taskId"];
        [param setObject:self.level1Name forKey:@"level1Name"];
        [param setObject:self.infoModel.level1Code forKey:@"level1Code"];
        [param setObject:exceptionDetails forKey:@"exceptionDetails"];
        
        NSLog(@"%@",param);
        
        [self.hud showAnimated:YES];
        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:SignException params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"success"] integerValue] == 0) {
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }else {
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = @"标记成功";
                    [weakSelf.hud hideAnimated:YES afterDelay:SuccessTime];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }];
        });
    }
}

#pragma mark - 背景view手势
- (void)bgViewClick:(UIGestureRecognizer *)tap {
    self.abnormalDetailButton.selected = !self.abnormalDetailButton.selected;
    [self.bgView removeFromSuperview];
    [UIView animateWithDuration:0.5 animations:^{
        self.signListView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, space(650));
    }];
}

#pragma mark - 数据请求
//加载部位列表数据
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.infoModel.level1Code forKey:@"level1Code"];
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:ConfigurationList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                NSArray *dataArray = responseObject[@"data"];
                [weakSelf.titleArray removeAllObjects];
                for (NSDictionary *dataDic in dataArray) {
                    ZCAbnormalListModel *listModel = [ZCAbnormalListModel yy_modelWithDictionary:dataDic];
                    if (self.level1Name == nil) {
                        self.level1Name = listModel.level1Name;
                    }
                    [weakSelf.titleArray addObject:listModel];
                }
                [weakSelf getRowHeight];
                [weakSelf.rightTableView reloadData];
                [weakSelf.leftTableView reloadData];
                [weakSelf.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
                
                [weakSelf loadExceptionListData];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

//估算高度
- (void)getRowHeight {
    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
    [attr setObject:[UIFont systemFontOfSize:FontSize(26)] forKey:NSFontAttributeName];
    for (ZCAbnormalListModel *listM in self.titleArray) {
        CGSize size = [listM.level2Name boundingRectWithSize:CGSizeMake(space(170), CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
        listM.rowHeight = size.height + space(60);
    }
}


- (void)loadExceptionListData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.taskType forKey:@"taskType"];
    if (self.orderNo.length > 0) {
        [param setObject:self.orderNo forKey:@"orderNo"];
    }else {
        [param setObject:@(0) forKey:@"orderNo"];
    }
    [param setObject:self.vin forKey:@"vin"];
    [param setObject:self.infoModel.level1Code forKey:@"level1Code"];
    
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:ExceptionPicUrl params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] integerValue] == 0) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }else {
                [weakSelf.hud hideAnimated:YES];
                for (NSDictionary *dic in responseObject[@"data"]) {
                    ZCAbnormalSignModel *signModel = [ZCAbnormalSignModel yy_modelWithDictionary:dic];
                    [weakSelf.signArray addObject:signModel];
                }
                weakSelf.numLabel.text = [NSString stringWithFormat:@"%zd",weakSelf.signArray.count];
                if (weakSelf.signArray.count > 0) {
                    weakSelf.numLabel.hidden = NO;
                }
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == _leftTableView) {
        return 1;
    }else {
        return self.titleArray.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        return self.titleArray.count;
    }else {
        ZCAbnormalListModel *listModel = (ZCAbnormalListModel *)self.titleArray[section];
        return listModel.exceptionDetail.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _leftTableView) {
        ZCAbnormalTitleTableViewCell *titleCell = [tableView dequeueReusableCellWithIdentifier:titleCellID forIndexPath:indexPath];
        titleCell.selectionStyle = UITableViewCellSelectionStyleNone;
        ZCAbnormalListModel *listModel = (ZCAbnormalListModel *)self.titleArray[indexPath.row];
        titleCell.title = listModel.level2Name;
        return titleCell;
    }else {
        ZCAbnormalDescTableViewCell *descCell = [tableView dequeueReusableCellWithIdentifier:descCellID forIndexPath:indexPath];
        descCell.selectionStyle = UITableViewCellSelectionStyleNone;
        descCell.delegate = self;
        descCell.index = indexPath;
        ZCAbnormalListModel *listModel = (ZCAbnormalListModel *)self.titleArray[indexPath.section];
        ZCAbnormalListDetailModel *detailModel = (ZCAbnormalListDetailModel *)listModel.exceptionDetail[indexPath.row];
        descCell.desc = detailModel.level3Name;
        return descCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _rightTableView) {
        return space(90);
    }
    ZCAbnormalListModel *listModel = (ZCAbnormalListModel *)self.titleArray[indexPath.row];
    return listModel.rowHeight > space(90) ? listModel.rowHeight : space(90);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        return CGFLOAT_MIN;
    }else {
        return space(90);
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        return [[UIView alloc] init];
    }else {
        UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH - space(210), space(90))];
        titleView.backgroundColor = ZCColor(0xe5f2ff, 1);
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(space(50), 0, space(360), space(80))];
        CGPoint point = label.center;
        point.y = titleView.center.y;
        label.center = point;
        ZCAbnormalListModel *listModel = (ZCAbnormalListModel *)self.titleArray[section];
        label.text = listModel.level2Name;
        label.textColor = ZCColor(0x000000, 0.87);
        label.font = [UIFont systemFontOfSize:FontSize(22)];
        [titleView addSubview:label];
        return titleView;
    }
    
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _leftTableView) {
        ZCAbnormalTitleTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.selected = YES;
        ZCAbnormalListModel *listModel = (ZCAbnormalListModel *)self.titleArray[indexPath.row];
        if (listModel.exceptionDetail.count > 0) {
             [self.rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.row] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }else {
        CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
        CGRect cellInScreenRect = [tableView convertRect:cellRect toView:[tableView superview]];
        CGRect buttonInScreenRect = cellInScreenRect;
        buttonInScreenRect.origin.x += cellInScreenRect.size.width - space(40) - 40;
        buttonInScreenRect.origin.y -= (cellInScreenRect.size.height - 40) / 2;
        buttonInScreenRect.size = CGSizeMake(40, 40);
        self.rectInScreen = buttonInScreenRect;
        [self takePhotoWith:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _leftTableView) {
        ZCAbnormalTitleTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.selected = NO;
    }
}

#pragma mark - ZCAbnormalDescTableViewCellDelegate
- (void)abnormalDescTableViewCellCameraButtonClickWithIndex:(NSIndexPath *)index rectInScreen:(CGRect)rect{
    self.rectInScreen = rect;
    [self takePhotoWith:index];
}

//抽取拍照方法
- (void)takePhotoWith:(NSIndexPath *)index {
    ZCAbnormalListModel *listModel = (ZCAbnormalListModel *)self.titleArray[index.section];
    ZCAbnormalListDetailModel *listDetailModel = (ZCAbnormalListDetailModel *)listModel.exceptionDetail[index.row];
    self.signModel = [[ZCAbnormalSignModel alloc] init];
    self.signModel.exLevel1 = listDetailModel.level1Code;
    self.signModel.exLevel2 = listDetailModel.level2Code;
    self.signModel.exLevel3 = listDetailModel.level3Code;
    self.signModel.level2Name = listDetailModel.level2Name;
    self.signModel.level3Name = listDetailModel.level3Name;
    ZCAbnormalListDetailModel *signDetailModel = [[ZCAbnormalListDetailModel alloc] init];
    self.signModel.exceptionDetails = @[signDetailModel];
    
    UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
    pickerVC.delegate = self;
    
    
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:pickerVC animated:YES completion:nil];
    }];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied ) {
            UIAlertController *alertStatus = [UIAlertController alertControllerWithTitle:@"应用相机权限受限" message:@"还没有打开相机权限，是否前往获取？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                NSURL *url2 = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url2];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"暂不" style:UIAlertActionStyleCancel handler:nil];
            [alertStatus addAction:okAction];
            [alertStatus addAction:cancelAction];
            [self presentViewController:alertStatus animated:YES completion:nil];
        }
        pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:pickerVC animated:YES completion:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:photoAction];
    [alertVC addAction:cameraAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    self.image = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        [self animationOfNextStepWithImage:self.image];
    }];

}

#pragma mark - 动画相关
- (void)animationOfNextStepWithImage:(UIImage *)image {
    if (!_layer) {
        _layer = [CALayer layer];
        _layer.contentsGravity = kCAGravityResizeAspectFill;
        _layer.bounds = CGRectMake(0, 0, 30, 30);
        _layer.masksToBounds = YES;
        _layer.cornerRadius = 15;
        _layer.position = CGPointMake(self.rectInScreen.origin.x, self.rectInScreen.origin.y);
        _layer.anchorPoint = CGPointMake(0, 0);
        [self.view.layer addSublayer:_layer];
    }
    _layer.contents = (__bridge id)image.CGImage;
    [self groupAnimation];
    
}

- (void)groupAnimation {
    _path = [UIBezierPath bezierPath];
    [_path moveToPoint:CGPointMake(self.rectInScreen.origin.x, self.rectInScreen.origin.y)];
    [_path addQuadCurveToPoint:CGPointMake(space(40), SCREENHEIGHT - space(90)) controlPoint:CGPointMake(SCREENWIDTH / 2, self.rectInScreen.origin.y)];
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.fillMode = kCAAnimationRotateAuto;
    
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation1.duration = 1;
    animation1.fromValue = @1.;
    animation1.toValue = @2.;
    animation1.timingFunction =
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    
    CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation2.duration = 1.;
    animation2.beginTime = 1;
    animation2.fromValue = @2.;
    animation2.toValue = @.5;
    animation2.timingFunction =
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    CABasicAnimation *animation0 = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation0.duration = 1;
    animation0.fromValue = @0;
    animation0.toValue = @(M_PI * 2);
    
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = @[ animation, animation0, animation1, animation2 ];
    group.duration = 1;
    group.removedOnCompletion = NO;
    group.fillMode = kCAFillModeForwards;
    group.delegate = self;
    [_layer addAnimation:group forKey:@"group"];
    
}


- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (anim == [_layer animationForKey:@"group"]) {
        [_layer removeFromSuperlayer];
        _layer = nil;
        
        [self getQiniuToken];
    }
}

#pragma mark - 上传图片
//获取七牛的token
- (void)getQiniuToken {

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool getWithURL:QiniuToken params:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                NSString *token = responseObject[@"data"];
                [weakSelf uploadImageToQiniuWithToken:token];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

//图片上传七牛
- (void)uploadImageToQiniuWithToken:(NSString *)qnToken {
    __weak typeof(self)weakSelf = self;
    QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
        builder.zone = [QNFixedZone zone2];
        builder.useHttps = YES;
    }];
    
    QNUploadManager *manager = [[QNUploadManager alloc] initWithConfiguration:config];
    NSData *imageData = UIImageJPEGRepresentation(self.image, 1);
    [manager putData:imageData key:nil token:qnToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSString *qnKey = resp[@"key"];
        ZCAbnormalListDetailModel *signDetailModel = (ZCAbnormalListDetailModel *)[self.signModel.exceptionDetails firstObject];
        signDetailModel.picKey = qnKey;
        [weakSelf downloadImageFromQiniuWithKey:qnKey];
        
    } option:nil];
    
}


//图片在七牛上的Url
- (void)downloadImageFromQiniuWithKey:(NSString *)qnKey {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:qnKey forKey:@"key"];
    NSLog(@"%@",param);
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool getWithURL:QiniuImageUrl params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] integerValue] == 1) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = @"照片上传成功";
                [weakSelf.hud hideAnimated:YES afterDelay:SuccessTime];
                ZCAbnormalListDetailModel *signDetailModel = (ZCAbnormalListDetailModel *)[weakSelf.signModel.exceptionDetails firstObject];
                signDetailModel.picUrl = (NSString *)responseObject[@"data"];
                
                [weakSelf addSign];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.hud showAnimated:YES];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            });
        }];
    });
}

//添加新的标记
- (void)addSign {
    BOOL find = NO;
    if (self.signArray.count == 0) {
        _num = [self.numLabel.text intValue] + 1;
        self.numLabel.hidden = NO;
        self.numLabel.text = [NSString stringWithFormat:@"%d", _num];
        [self.signArray addObject:self.signModel];
    }else {
        for (ZCAbnormalSignModel *sModel in self.signArray) {
            if ([sModel.exLevel1 isEqualToString:self.signModel.exLevel1] && [sModel.exLevel2 isEqualToString:self.signModel.exLevel2] && [sModel.exLevel3 isEqualToString:self.signModel.exLevel3]) {
                NSMutableArray *tempA = [NSMutableArray arrayWithArray:sModel.exceptionDetails];
                [tempA addObject:[self.signModel.exceptionDetails firstObject]];
                sModel.exceptionDetails = [tempA copy];
                find = YES;
            }else {
                continue;
            }
        }
        if (!find) {
            _num = [self.numLabel.text intValue] + 1;
            self.numLabel.hidden = NO;
            self.numLabel.text = [NSString stringWithFormat:@"%d", _num];
            [self.signArray addObject:self.signModel];
        }
    }
    self.signModel = nil;
}

#pragma mark - ZCAbnormalSignListViewDelegate
- (void)abnormalSignListViewScanActionWithImaA:(NSMutableArray *)imaga index:(NSIndexPath *)index {
    ZCAbnormalScanPhotoViewController *scanVC = [[ZCAbnormalScanPhotoViewController alloc] init];
    scanVC.dataArray = [imaga copy];
    scanVC.nowIndex = index;
    [self.navigationController pushViewController:scanVC animated:YES];
}

- (void)abnormalSignListViewLongPressImageWithSignArray:(NSArray *)signArray {
    self.signArray = [signArray mutableCopy];
    self.numLabel.text = [NSString stringWithFormat:@"%zd",self.signArray.count];
    if (self.signArray.count == 0) {
        self.numLabel.hidden = YES;
        [self.bgView removeFromSuperview];
        [UIView animateWithDuration:0.5 animations:^{
            self.signListView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, space(650));
        }];
    }
}

#pragma mark - 布局
- (void)updateViewConstraints {
    [super updateViewConstraints];
    __weak typeof(self)weakSelf = self;
    
    [_handleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
        make.height.mas_equalTo(space(90));
    }];
    
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).offset(space(40));
        make.centerY.equalTo(weakSelf.handleView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(space(42), space(42)));
    }];
    
    [_numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(weakSelf.imageView.mas_right);
        make.centerY.equalTo(weakSelf.imageView.mas_top).offset(space(4));
        make.size.mas_equalTo(CGSizeMake(space(60), space(30)));
        make.left.equalTo(weakSelf.imageView.mas_right).offset(-space(10));
    }];
    
    [_abnormalDetailButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.imageView.mas_right).offset(space(40));
        make.right.equalTo(weakSelf.signButton.mas_left).offset(-space(40));
        make.top.equalTo(weakSelf.handleView.mas_top);
        make.bottom.equalTo(weakSelf.handleView.mas_bottom);
    }];
    
    [_signButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.handleView.mas_top);
        make.bottom.equalTo(weakSelf.handleView.mas_bottom);
        make.right.equalTo(weakSelf.handleView.mas_right);
        make.width.mas_equalTo(space(260));
    }];
    
    [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.handleView.mas_left);
        make.right.equalTo(weakSelf.handleView.mas_right);
        make.top.equalTo(weakSelf.handleView.mas_top);
        make.height.mas_equalTo(space(2));
    }];
}

@end
